package com.aierkeji.call.b2c.service;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aierkeji.call.b2c.contants.Contants;
import com.aierkeji.call.b2c.dao.jpa.AkjCallClueDao;
import com.aierkeji.call.b2c.dao.jpa.AkjCallClueHistoryDao;
import com.aierkeji.call.b2c.dao.jpa.AkjCallUpdateErrorClueHistoryDao;
import com.aierkeji.call.b2c.entity.AkjCallClue;
import com.aierkeji.call.b2c.entity.AkjCallClueHistroy;
import com.aierkeji.call.b2c.entity.AkjCallClueVo;
import com.aierkeji.call.b2c.entity.AkjCallUpdateErrorClueHistory;
import com.aierkeji.call.b2c.entity.AkjCallUser;
import com.aierkeji.call.b2c.entity.PageBean;
import com.aierkeji.call.b2c.entity.snap.AkjCallUserSnap;
import com.aierkeji.call.b2c.util.DateTimeUtils;
import com.aierkeji.call.b2c.util.GsonUtils;
import com.aierkeji.call.b2c.util.ResultMapHelper;
import com.aierkeji.call.b2c.util.StringUtils;

@Service
public class AkjCallClueService {
	private final Logger log = LogManager.getLogger(getClass());
	
	@Autowired
	private AkjCallClueDao akjCallClueDao;
	
	@Autowired
	private AkjCallClueHistoryDao akjCallClueHistoryDao;
	
	@Autowired
	private AkjCallUpdateErrorClueHistoryDao akjCallUpdateErrorClueHistoryDao;
	
	
	public Map<String, Object> findCallClue(Map<String, Object> map) {
		PageBean<AkjCallClueVo> cluesList = null;
		try {
			String page = (String)map.get("page");
			int size = Contants.PAGE_SIZE;
			
			if (StringUtils.isEmpty(page)) {
				return ResultMapHelper.nullParamsResult();
			}
			AkjCallUser user = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
			
			cluesList = akjCallClueDao.findCallClueByAssignedToAndAssignedAtForPage(user, map, size);
					
		}catch (Exception e) {
			log.error("AkjCallClueService.findCallClue is fault", e,map);
			return ResultMapHelper.failure("系统出错拉，查询失败");
		}
		
		return ResultMapHelper.success(cluesList);
	}

    @Transactional(rollbackFor = Exception.class)
	public Map<String, Object> uploadCallClue(Map<String, Object> map, HttpServletRequest request) {
		
		String lastCallAt		= (String)map.get("callAt");
		String callClueId 		= (String)map.get("clueId");
		String phone 			= (String)map.get("phone");
		String groupId 			= (String)map.get("groupId");
		String isExtra 			= (String)map.get("isExtra");
		
		if(StringUtils.checkAnyNull(lastCallAt,callClueId,phone,groupId)) {
			return ResultMapHelper.nullParamsResult();
		}
		
		AkjCallUser akjCallUser = (AkjCallUser) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
		if ("0".equals(callClueId)) {
			Long dbClueId = this.akjCallClueDao.findClueId(phone,akjCallUser.getId(),Long.parseLong(groupId));
			log.info("query DB clue id :{},phone:{} ,user:{},group:{}", dbClueId, phone, akjCallUser.getId(), groupId);
			if(dbClueId!=null&&dbClueId>0) {
				callClueId = dbClueId+"";
				map.put("clueId", callClueId);
				map.put("isExtra", "9"+isExtra);
				
			}else {
			}
		}
		
		map.put("userId", akjCallUser.getId());
			
		boolean flag = akjCallClueDao.updateByid(map);
		
		if(!flag) {
			//这个log以后需要删
			log.info("AkjCallClueService.uploadCallClue ---- callClueId :{} ------phone:{}---userId--:{}--- version :{}---- call at :{}",
					callClueId,
					phone,
					akjCallUser.getId(),
					akjCallUser.getVersion(),
					lastCallAt);
			
			try {
				String isSaveError  = 	System.getProperty("isSaveError","true");
				if("true".equals(isSaveError)) {
					AkjCallUpdateErrorClueHistory akjCallUpdateErrorClueHistory = GsonUtils.transMapToObj(map, AkjCallUpdateErrorClueHistory.class);
					akjCallUpdateErrorClueHistory.setCreatedAt(DateTimeUtils.getCurrentTime());
					akjCallUpdateErrorClueHistory.setCreatedBy(AkjCallUserSnap.build(akjCallUser));
					akjCallUpdateErrorClueHistory.setVersion(request.getHeader("versionName"));
					akjCallUpdateErrorClueHistoryDao.save(akjCallUpdateErrorClueHistory);
				}
			}catch (Exception e) {
				// TODO: handle exception
				log.error("",e);
			}
			log.info("AkjCallClueService.uploadCallClue ------------------update callClue error because DB not found data");
			Map<String,Object> resut2 = ResultMapHelper.initMap();
			resut2.put("msg", "更新线索失败!");
			return ResultMapHelper.success(resut2);
		}
		
		AkjCallClueHistroy akjCallClueHistroy = GsonUtils.transMapToObj(map, AkjCallClueHistroy.class);
		akjCallClueHistroy.setCreatedAt(DateTimeUtils.getCurrentTime());
		akjCallClueHistroy.setCreatedBy(AkjCallUserSnap.build(akjCallUser));
		akjCallClueHistroy.setVersion(request.getHeader("versionName"));
		akjCallClueHistoryDao.save(akjCallClueHistroy);
		
//		AkjCallClue akjCallClueO =  akjCallClueDao.findById(Long.valueOf(callClueId));
//		
//		
//		
//		if (!phone.equals(akjCallClueO.getPhone())) {
//			log.info("lod put phone "+phone +"db phone"+akjCallClueO.getPhone());
//			return ResultMapHelper.failure("号码与ID不一致");
//		}
		
		
		
		
		
//			boolean updateStatisicsFlag = updateCallClueStatisics(lastCallAt,akjCallUser.getId(),phone);
//			if(!updateStatisicsFlag) {
//				return ResultMapHelper.failure("更新统计数据失败");
//			}
		return ResultMapHelper.success();
	}
	
//	private boolean updateCallClueStatisics(String lastCallAt,Long userId,String phone) throws Exception{
//		List<AkjCallClueVo> callClueVos	 = akjCallClueDao.findByIdAndcallClueIdAndPhone(lastCallAt,userId,phone);
//		AkjCallClueStatistics callClueStatistics = aCallClueStatisticsDao.findByCallUserIdACreatedAt(id)
//		
//		
//		
//		for(AkjCallClueVo vo : callClueVos) {
//			Long lastCallTime 		= vo.getLastCallTime();
//			Long clueGroupId 		= vo.getGroupId();
//			Date lastCallAtDate		= vo.getLastCallAt();
//			CallStatus callStatus 	= CallStatus.valueOf(vo.getLastCallStatus());
//			CallResult callResult 	= CallResult.valueOf(vo.getLastCallResult());
//
//			//该线索第一次呼叫
//			if(calClueVos.size()==0) {
//				
//			}
//			
//		}
//		
//		
//		
//		return false;
//	}


	public Map<String, Object> findCallClueDetail(Map<String, Object> map) {
		String callClueId = (String)map.get("callClueId");
		
		AkjCallClueVo akjCallClueVo = new AkjCallClueVo();
		try {
			AkjCallClue akjCallClue = akjCallClueDao.findById(Long.valueOf(callClueId));
			
			BeanUtils.copyProperties(akjCallClueVo,akjCallClue);
		}catch(Exception e) {
			e.printStackTrace();
			return ResultMapHelper.failure("查询线索详情失败");
		}
		return ResultMapHelper.success(akjCallClueVo);
	}

}
